package bold.deposit;

import bold.deposit.interception.NoAuthorize;
import bold.deposit.useful.CookieUtil;
import bold.deposit.useful.JWTUtil;
import bold.deposit.useful.Redis;
import bold.deposit.useful.Result;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

@RestController
@NoAuthorize
public class LoginController {
    @Autowired
    private Redis redis;

    private final int LOGIN_TIME = 1;
    private final TimeUnit TIME_UNIT = TimeUnit.MINUTES;

    @RequestMapping("login")
    public Result login(HttpServletResponse response) {
        Account account = new Account();
        account.setId("1");
        account.setName("name");
        return new Result(this.login(account, response));
    }

    /**
     * 需要注入
     * 1、设置cookie token
     * 2、redis 登录
     * 3、redis 单点登录
     */
    private boolean login(Account account, HttpServletResponse response) {
        String key = JWTUtil.token(account, LOGIN_TIME, TIME_UNIT);
        CookieUtil.set(response, "token", key);

        String idValue = redis.get(account.getId(), "");
        if (!"".equals(idValue)) {
            redis.delete(idValue);
        }
        redis.set(account.getId(), key, LOGIN_TIME, TIME_UNIT);
        return redis.set(key, JSON.toJSONString(account), LOGIN_TIME, TIME_UNIT);
    }
}
